package me.fung.wubi.base.define.table

import me.fung.wubi.base.define.value.Code
import me.fung.wubi.base.define.value.Word
import me.fung.wubi.base.define.value.toCode
import me.fung.wubi.base.define.value.toWord
import me.fung.wubi.base.io.autoReadLines
import java.io.File

/**
 * 单字码表
 */
class Lexicon(
    mutableMap: MutableMap<Word, Code> = HashMap()
) : MutableMap<Word, Code> by mutableMap {
    fun loadFromFile(file: File): Lexicon {
        file.autoReadLines().forEach FE@{
            if (it.startsWith("#")) return@FE
            val list = it.split(' ', '\t')
            if (list.size > 1) {
                put(list[1].toWord(), list[0].toCode())
            }
        }
        return this
    }

    fun codeOfWord(word: Word): Code {
        return get(word) ?: throw IllegalStateException("Cannot find code of $word")
    }

    fun codeOrNull(word: Word): Code? {
        return get(word)
    }
}

fun Lexicon(file: File): Lexicon = Lexicon().apply { loadFromFile(file) }
